package email;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLStreamException;

public class DBTest {

	public static void main(String[] args) throws FileNotFoundException, XMLStreamException, FactoryConfigurationError, ParseException {
	
		DBController db = new DBController("C:/Users/Ted/Desktop");
		
		/*
		String str = "Tue Nov 15 18:29:34 CST 2011";
		DateFormat fmt = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");
		Date d = fmt.parse(str);
		System.out.println(d.getTime());
		*/


		Map<String, String> attributes;
		
		long threadId = -1;
		attributes = new HashMap<String, String>();
		List<Thread> threads = db.getAllThreads();
		if (threads.size() >= 1) {
			threadId = threads.get(0).getId();
		}
		attributes.put("id", "" + threadId);
		threads = db.selectThread(attributes);
		Thread thr = new Thread();
		for (Thread t : threads) {
			thr = t;
			System.out.println(t);
			for (ReceivedMessage m : t.getEmails()) {
				System.out.print(m + ";");
			}
			System.out.println();
		}
		
		db.rename(threadId, thr, "Poopy");
		threads = db.selectThread(attributes);
		if (threads.size() > 0) {
			thr = threads.get(0);
			System.out.println(threads.get(0));
		}	
		
		db.unthread(thr);
		threads = db.selectThread(attributes);
		if (threads.size() == 0) {
			System.out.println("Successfully unthreaded");
		} else {
			System.out.println("unthread fail");
		}
		
		threads = db.getAllThreads();
		if (threads.size() > 2) {
			Thread t1 = threads.get(0);
			Thread t2 = threads.get(1);
			
			System.out.println("Merging " + t1 + " and " + t2);
			
			long ids[] = {t1.getId(), t2.getId()};
			thr = new Thread();
			for (ReceivedMessage m : t1.getEmails()) {
				thr.addEmail(m);
			}
			for (ReceivedMessage m : t2.getEmails()) {
				thr.addEmail(m);
			}
			
			thr.setName("Merged Thread!");
			thr.setId(thr.hashCode());
			
			System.out.println("Merged Thread: " + thr);
			
			db.mergeThread(ids, thr);
			
			attributes.put("id", thr.getId() + "");
			
			threads = db.selectThread(attributes);
			for (Thread t : threads) {
				System.out.println("DB has " + t);
			}
		} else {
			System.out.println("Not enough Threads..." + threads.size());
		}
	}
}
